package club.zhcs.cms.module;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.json.Json;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.View;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Attr;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import club.zhcs.cms.Application.SessionKeys;
import club.zhcs.cms.bean.system.acl.User;
import club.zhcs.cms.biz.shiro.ShiroUserService;

import com.kerbores.nutz.captcha.JPEGView;
import com.kerbores.nutz.module.base.AbstractBaseModule;
import com.kerbores.utils.encode.DES;
import com.kerbores.utils.entries.Result;

/**
 * 
 * @author Kerbores(kerbores@gmail.com)
 *
 * @project thunder-web
 *
 * @file SystemModule.java
 *
 * @description //TODO
 *
 * @time 2016年3月8日 上午10:51:26
 *
 */
@At("system")
public class SystemModule extends AbstractBaseModule {

	@Inject
	ShiroUserService shiroUserService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.kerbores.nutz.module.base.AbstractBaseModule#_getNameSpace()
	 */
	@Override
	public String _getNameSpace() {
		return "system";
	}

	// 此处前台是json请求所以会返回json串
	@At
	@Filters
	public Result login(@Param("user") String user, @Param("password") String password, @Param("captcha") String captcha, @Param("rememberMe") boolean rememberMe,
			HttpSession session) {
		if (Strings.equalsIgnoreCase(captcha, session.getAttribute(JPEGView.CAPTCHA).toString())) {
			Result result = shiroUserService.login(user, password);
			if (result.isSuccess()) {
				// 登录成功处理
				_putSession(SessionKeys.USER_KEY, result.getData().get("loginUser"));
				if (rememberMe) {
					NutMap data = NutMap.NEW();
					data.put("user", user);
					data.put("password", password);
					data.put("rememberMe", rememberMe);
					_addCookie("kerbores", DES.encrypt(Json.toJson(data)), 24 * 60 * 60 * 365);
				}
			}
			return result;
		} else {
			return Result.fail("验证码输入错误");
		}
	}

	@At
	@Ok(">>:/apm/dashboard")
	public Result main() {
		return Result.success();
	}

	@At("/logout")
	public View logOut() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
		if (log.isDebugEnabled()) {
			log.debug("用户退出登录");
		}
		return _renderRedirct("/");
	}

	@At
	@Ok("beetl:pages/admin/settings.html")
	public Result settings(@Attr(SessionKeys.USER_KEY) User user) {
		return Result.success().addData("user", user);
	}
}
